package com.sto.stoapp.activity.sales;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.activity.scanner.StoSelectTableActivity;
import com.sto.stoapp.dataprocess.ProcessScanCode;
import com.sto.stoapp.dataprocess.parcelable.GetTableParcel;
import com.sto.stoapp.dataprocess.parcelable.SelectTableParcel;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.constant.StoServerSmsConstant;
import com.sto.stoapp.db.manager.SqlSelectTableManager;
import com.sto.stoapp.entity.DataBusinessEntity;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.status.EnumScanCode;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.util.BillFilterUtil;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;
import com.sto.stoapp.widget.StoListenerActivity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressLint("HandlerLeak")
public class SalesServerPointSmsActivity extends StoListenerActivity {

	private StoHhmEditText pointCode;
	private StoHhmEditText pointAddr;
	private StoHhmEditText pointTel;
	private StoHhmEditText phone;
	// private StoHhmEditText code;
	private List<EditText> edit = new ArrayList<EditText>();
	private final int POINTCODE_RESULT = 0xfe;
	private DataBusinessEntity dataBusiness;

	/**
	 * 扫描码判断
	 * 
	 * @param code
	 *            扫描码
	 * @return true/ok or false
	 */
	private boolean CheckScanCode(String code) {
		boolean ret = false;

		EnumScanCode status = ProcessScanCode.getInstance(this)
				.ScanCodeResolve(code, EnumTableNames.STATUS_TABLE_SERVICE_SMS);
		switch (status) {
		// 条码空
		case CODE_EMPTY:
			// Helper.showSoundToast(SalesServerPointSmsActivity.this,
			// getString(R.string.code_empty), false);

			break;

		// 非法条码
		case CODE_ILLEGAL:
			Helper.showSoundToast(SalesServerPointSmsActivity.this,
					getString(R.string.error_code), false);
			break;
		// 成功条码
		case CODE_WAY_BILL:

			ret = true;
			break;
		default:
			break;
		}

		return ret;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sto_sales_server_sms);
		Bundle extras = getIntent().getExtras();

		this.setTitleBottom(R.string.server_point_sms,
				extras.getString("busiType"));
		initPointLayout(true);
		initWidget();
		initListen();
		initScanListener();
		dataBusiness = new DataBusinessEntity();
		dataBusiness.initInsertData();
		initScanRecordAdapter(EnumTableNames.STATUS_TABLE_SERVICE_SMS);
	}

	private void initWidget() {
		pointCode = (StoHhmEditText) this.findViewById(R.id.server_mark_text);
		pointAddr = (StoHhmEditText) this
				.findViewById(R.id.server_point_addr_text);
		pointTel = (StoHhmEditText) this
				.findViewById(R.id.server_point_tel_text);
		pointAddr.setEnabled(false);
		pointTel.setEnabled(false);
		phone = (StoHhmEditText) this
				.findViewById(R.id.server_point_phone_text);
		code = (StoHhmEditText) this
				.findViewById(R.id.waybill_serial_numbers_text);
		// pointAddr.setInputType(InputType.TYPE_CLASS_TEXT);
		// pointTel.setInputType(InputType.TYPE_CLASS_PHONE);
		edit.add(pointCode);
		addUploadTable(EnumTableNames.STATUS_TABLE_SERVICE_SMS);
		// edit.add(code);

	}

	/**
	 * 监听控件
	 */
	@SuppressLint("NewApi")
	private void initListen() {

		// pointCode.setOnClickListener(new StoOnClickListener(this) {
		// @Override
		// public void mHonClick(View view) {
		// SelectInfo();
		// }
		// });
		pointCode.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				onBackPressed();
			}

			@Override
			public void onEditClickListener(View v) {
//				SelectInfo();
			}
		});

		findViewById(R.id.btn_select).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				SelectInfo();
			}
		});

		pointAddr.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				pointCode.requestFocus();
			}

			@Override
			public void onEditClickListener(View v) {
				pointTel.requestFocus();
			}
		});
		pointTel.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				pointAddr.requestFocus();
			}

			@Override
			public void onEditClickListener(View v) {
				phone.requestFocus();
			}
		});

		phone.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				pointCode.requestFocus();
			}

			@Override
			public void onEditClickListener(View v) {
				if (phone.getText().toString().length() > 0) {
					if (isMobileNO(phone.getText().toString())) {
						code.requestFocus();
					} else {
						Helper.showSoundToast(SalesServerPointSmsActivity.this,
								"手机号不合法!", false);
						phone.setText("");
					}

				} else {
					Helper.showSoundToast(SalesServerPointSmsActivity.this,
							"手机号码不能为空!", false);
				}

			}
		});


		code.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				phone.requestFocus();
			}

			@Override
			public void onEditClickListener(View v) {
				if (code.getText().length() <= 0) {
					Helper.showSoundToast(SalesServerPointSmsActivity.this,
							getString(R.string.code_empty), false);
					return;
				} else {
					handlerScanData(code.getText().toString());
				}
			}
		});

		/*
		 * code.setEditScanListener(new EditScanListener() {
		 * 
		 * @Override public void onScan() { ScanOpen(); }
		 * 
		 * @Override public void offScan() { ScanOff(); } });
		 */
		/*
		 * code.setOnClickListener(new StoOnClickListener(this) {
		 * 
		 * @Override public void mHonClick(View view) { if (CheckItem()) {
		 * onScanResults(code.getText().toString()); } } });
		 */

		for (EditText editListener : edit) {
			/*
			 * 监听EditText内容个数
			 */
			editListener.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start,
						int before, int count) {
					// 控件没有内容就清空编号

					if (pointCode.getText().toString().isEmpty()) {
						pointAddr.setText("");
						pointTel.setText("");
					}

				}

				@Override
				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {
				}

				@Override
				public void afterTextChanged(Editable s) {

				}
			});
		}

	}

	private boolean CheckItem() {
		boolean ret = true;
		if (pointCode.getText().length() == 0) {
			Helper.showSoundToast(SalesServerPointSmsActivity.this,
					"请输入服务点代码!", false);
			ret = false;
			pointCode.requestFocus();
			return ret;
		}
		/*
		 * if (pointAddr.getText().length() == 0) {
		 * Helper.showSoundToast(SalesServerPointSmsActivity.this, "请输入服务点地址!",
		 * false); ret = false; pointAddr.requestFocus(); return ret; } if
		 * (pointTel.getText().length() == 0) {
		 * Helper.showSoundToast(SalesServerPointSmsActivity.this, "请输入服务点电话!",
		 * false); ret = false; pointTel.requestFocus(); return ret; }
		 */
		if (phone.getText().length() == 0) {
			Helper.showSoundToast(SalesServerPointSmsActivity.this, "请输入手机号码!",
					false);
			ret = false;
			phone.requestFocus();
			return ret;
		}
		if (isMobileNO(phone.getText().toString()) == false) {
			Helper.showSoundToast(SalesServerPointSmsActivity.this, "手机号不合法!",
					false);
			ret = false;
			phone.requestFocus();
		}
		return ret;
	}

	/**
	 * 手机号判断
	 * 
	 * @param mobiles
	 * @return
	 */
	private boolean isMobileNO(String mobiles) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(17[0-9])|(15[0-9])|(18[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	/**
	 * 选择列表返回的结果
	 */
	private void SelectInfo() {
		try {
			SelectTableParcel tableParcel = new SelectTableParcel();
			if (pointCode.getText().length() == 0) {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_SERVER_SMS_ALL);
				tableParcel.setSelectField(new String[] {});
			} else {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_SERVER_SMS_ONLY);
				tableParcel.setSelectField(new String[] { "%"
						+ pointCode.getText().toString() + "%" });
			}

			tableParcel.setSelectCode(StoServerSmsConstant.SERVER_SMS_SITECODE);
			tableParcel.setSelectName(StoServerSmsConstant.SERVER_SMS_ADDRESS);
			tableParcel.setProperty(StoServerSmsConstant.SERVER_SMS_PHONE);

			Intent intent = new Intent(SalesServerPointSmsActivity.this,
					StoSelectTableActivity.class);
			intent.putExtra("tableData", tableParcel);

			startActivityForResult(intent, POINTCODE_RESULT);

		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("SelectInfo", e.getMessage());
		}
	}

	/**
	 * 选择列表返回的结果
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == POINTCODE_RESULT && resultCode == RESULT_OK) {
			GetTableParcel courierEntity = data.getParcelableExtra("Name");
			if (courierEntity != null) {
				pointCode.setText(courierEntity.getSelectCode());
				pointAddr.setText(courierEntity.getSelectName());
				pointTel.setText(courierEntity.getProperty());

				// if (recvPresonCode.length() > 0)
				phone.requestFocus();
			}
		} else if (requestCode == POINTCODE_RESULT
				&& resultCode == RESULT_FIRST_USER) {
			pointCode.setText("");
			pointAddr.setText("");
			pointTel.setText("");
			Helper.showSoundToast(SalesServerPointSmsActivity.this,
					getString(R.string.undefined), false);
		} else {

		}
	}

	// 处理扫描数据
	@SuppressLint("NewApi")
	private void processScanData() {
		try {

			//Add by wj过滤单号
			boolean isFilter= BillFilterUtil.isFilter(code.getText().toString().trim(),this);
			if(isFilter){
				showFilterDialog(code.getText().toString().trim());
				return;
			}
			//End by wj

			if (addPieceRecord()) {
				this.addCodeNumber();
				setSaveData(true);
				// SoundManager.getInstance(this).playSuccessSound();
				Helper.showSoundAndVibrator(this, true);
				code.setSelection(code.length());
				addScanRecordInfo(code.getText().toString());
				phone.setText("");
				code.setText("");
				phone.requestFocus();
			}
			// 提示插入数据失败
			else {
				Helper.showSoundToast(SalesServerPointSmsActivity.this,
						getString(R.string.code_repeat), false);
			}

			ScanOpen();

		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("processScanData", e.getMessage());
		}
	}

	// 增加一条记录
	@SuppressLint("SimpleDateFormat")
	private boolean addPieceRecord() {
		boolean ret;

		// 运单编号
		dataBusiness.setBar_code_number(code.getText().toString());

		dataBusiness.setCodeType(getExpType(code.getText().toString()));
		// 服务点代码
		dataBusiness.setNext_station(pointCode.getText().toString());
		// 服务点地址
		dataBusiness.setUser_defined3(pointAddr.getText().toString());
		// 服务点电话
		dataBusiness.setSend_phone(pointTel.getText().toString());
		// 手机号码
		dataBusiness.setRemark_name(phone.getText().toString());
		// 序号
		dataBusiness.setDifferent_flag((new SimpleDateFormat("yyyyMMddHHmmss")
				.format(new Date())));
		// 网点编号
		dataBusiness.setNet_code(StoFilePreference.getInstance(this)
				.getSiteCode());

		ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
				EnumTableNames.STATUS_TABLE_SERVICE_SMS);
		return ret;
	}

	@Override
	public void onBackPressed() {
		// 确定退出吗?
		showNotice();
		// super.onBackPressed();

	}

	@Override
	protected void onDestroy() {
		edit.clear();
		super.onDestroy();
	}

	@Override
	protected void handlerScanData(String scanData) {

		if (scanData != null && !scanData.equals("")) {
			String result = scanData;
			code.setText(result);
			if (CheckItem()) {

				if (CheckScanCode(result)) {
					processScanData();
				}
			}
			code.setText("");
		}

	}
}
